package com.android.pI;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.net.ParseException;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class UpdaterService extends Service {
	private static final String TAG = UpdaterService.class.getSimpleName();
	private Updater updater;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		updater = new Updater();

		Log.d(TAG, "onCreate'd");
	}

	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		// Start the updater
		if (!updater.isRunning()) {
			updater.start();
		}

		Log.d(TAG, "onStart'd");
	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();

		// Stop the updater
		if (updater.isRunning()) {
			updater.interrupt();
		}

		updater = null;

		Log.d(TAG, "onDestroy'd");
	}

	// ///// Updater Thread
	class Updater extends Thread {
		private JSONArray jArray;
		private String result = null;
		private InputStream is = null;
		private StringBuilder sb = null;
		private static final long DELAY = 60000; // one minute
		private boolean isRunning = false;

		public Updater() {
			super("Updater");
		}

		@Override
		public void run() {
			isRunning = true;
			while (isRunning) {
				try {
					// Do something
					Log.d(TAG, "Updater run'ing");

					// Open Database
					DataBaseHelper dbHelper = new DataBaseHelper(
							UpdaterService.this);

					// json part
					ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

					// http post
					try {
						HttpClient httpclient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost(
								"http://10.0.2.2:8000/city.php");
						httppost.setEntity(new UrlEncodedFormEntity(
								nameValuePairs));
						HttpResponse response = httpclient.execute(httppost);
						HttpEntity entity = response.getEntity();
						is = entity.getContent();
					} catch (Exception e) {
						Log.e("log_tag",
								"Error in http connection" + e.toString());
					}
					// convert response to string
					try {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						is.close();
						result = sb.toString();
					} catch (Exception e) {
						Log.e("log_tag",
								"Error converting result " + e.toString());
					}
					// paring data
					int _id;
					String ex_image;
					String ex_name;
					int wk_id;
					long ex_time;
					int ex_place;
					ContentValues values = new ContentValues();

					try {
						jArray = new JSONArray(result);
						JSONObject json_data = null;
						for (int i = 0; i < jArray.length(); i++) {
							json_data = jArray.getJSONObject(i);
							_id = json_data.getInt("_id");
							ex_image = json_data.getString("ex_image");
							ex_name = json_data.getString("ex_name");
							wk_id = json_data.getInt("wk_id");
							ex_time = json_data.getLong("ex_time");
							ex_place = json_data.getInt("ex_place");

							// Create content values
							values.put("_id", _id);
							values.put("ex_image", ex_image);
							values.put("ex_name", ex_name);
							values.put("wk_id", wk_id);
							values.put("ex_time", ex_time);
							values.put("ex_place", ex_place);
							
							// update exercises
							dbHelper.UpdaterEx(values);
							
						}
					} catch (JSONException e1) {
						Toast.makeText(getBaseContext(), "No Updates",
								Toast.LENGTH_LONG).show();
					} catch (ParseException e1) {
						e1.printStackTrace();
					}
					
					// Close Database
					dbHelper.close();

					// Sleep
					Thread.sleep(DELAY);
				} catch (InterruptedException e) {
					// Interrupted
					isRunning = false;
				}
			} // while
		}
		public boolean isRunning() {
			return this.isRunning;
		}

	}

}
